<?php

namespace App\Listeners;

use App\Repository\Models\Orders;
use App\Repository\Repositories\ItemsCrontabsRepositoryEloquent;
use App\Repository\Repositories\ItemsInformationRepositoryEloquent;
use Mockery\Exception;

class ItemListener
{
    private $item_repo;
    private $item_crontab;

    public function __construct(ItemsInformationRepositoryEloquent $item_repo,ItemsCrontabsRepositoryEloquent $item_crontab)
    {
        $this->item_repo= $item_repo;
        $this->item_crontab= $item_crontab;
    }

    public function subscribe($events)
    {
        $events->listen(
            'App\Events\ItemEvent',
            'App\Listeners\ItemListener@affirm'
        );

    }

    /**
     * @param $event:data['item_id']
     * @return bool
     */
    public function affirm($event)
    {
        $data = $event->data;
        $update = [
            'order_status' => Orders::ORDER_STATUS_CANCEL,
        ];

        \DB::beginTransaction();
        try{
            //更新配单状态
            $order=Orders::query()->where('id',$data['order_id'])->update($update);

            //更新定时任务记录表
            $this->item_crontab->affirmDone($data['order_id']);

            \DB::commit();
            $ret = true;
        }catch(Exception $e){
            \DB::rollback();
            $ret = false;
        }

        return $ret ? true : false;
    }


}
